<template>
  <view class="history-container">
    <!-- 历史记录列表 -->
    <scroll-view 
      scroll-y 
      class="history-scroll"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <!-- 空状态 -->
      <view v-if="historyList.length === 0" class="empty-state">
        <image src="/static/images/empty-history.png" mode="aspectFit"></image>
        <text class="empty-text">暂无浏览记录</text>
        <button class="go-browse" @tap="goBrowse">去逛逛</button>
      </view>

      <!-- 历史记录列表 -->
      <view v-else class="history-list">
        <view class="list-header">
          <text></text>
          <text class="clear-btn" @tap="handleClearAll">清空</text>
        </view>
        <view 
          class="history-item"
          v-for="item in historyList" 
          :key="item.id"
        >
          <!-- 商品信息 -->
          <view class="product-info" @tap="toProductDetail(item.productId)">
            <image :src="item.mainImage" mode="aspectFill" class="product-image"></image>
            <view class="info">
              <text class="name">{{ item.productName }}</text>
              <text class="price">¥{{ item.price }}</text>
              <text class="time">{{ formatDate(item.browseTime) }}</text>
            </view>
          </view>
          
          <!-- 删除按钮 -->
          <view class="delete-btn" @tap="handleDelete(item.id)">
            <uni-icons type="trash" size="20" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus" v-if="historyList.length > 0"></uni-load-more>
    </scroll-view>
  </view>
</template>

<script>
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      historyList: [],
      pageNum: 1,
      pageSize: 10,
      isRefreshing: false,
      loadMoreStatus: 'more',
      hasMore: true
    }
  },

  onLoad() {
    this.loadHistoryList()
  },

  methods: {
    formatDate,
    
    // 加载浏览历史列表
    async loadHistoryList(refresh = false) {
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }

      if (!this.hasMore) return

      try {
        this.loadMoreStatus = 'loading'
        
        // 显示加载提示
        if (!refresh) {
          uni.showLoading({
            title: '加载中...',
            mask: true
          })
        }

        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        const { data: res } = await this.$api.user.history.list(params)

        // 隐藏加载提示
        if (!refresh) {
          uni.hideLoading()
        }

        if (res && res.records) {
          // 格式化数据
          const formattedRecords = res.records.map(item => ({
            id: item.id,
            productId: item.productId,
            productName: item.productName,
            mainImage: item.productImage,
            price: item.productPrice,
            description: item.productDescription,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            viewCount: item.viewCount,
            stayDuration: item.stayDuration,
            browseTime: Array.isArray(item.lastViewTime) 
              ? `${item.lastViewTime[0]}-${item.lastViewTime[1]}-${item.lastViewTime[2]} ${item.lastViewTime[3]}:${item.lastViewTime[4]}:${item.lastViewTime[5]}`
              : item.lastViewTime
          }))

          if (refresh) {
            this.historyList = formattedRecords
          } else {
            this.historyList = [...this.historyList, ...formattedRecords]
          }

          // 更新分页状态
          this.hasMore = this.historyList.length < res.total
          this.pageSize = res.size
          this.pageNum = res.current
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
        } else {
          this.loadMoreStatus = 'noMore'
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载浏览历史失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.loadMoreStatus = 'more'
      } finally {
        if (refresh) {
          this.isRefreshing = false
        }
        uni.hideLoading()
      }
    },

    // 删除单条浏览记录
    async handleDelete(id) {
      try {
        const res = await uni.showModal({
          title: '提示',
          content: '确定要删除这条浏览记录吗？',
          confirmColor: '#ff5500'
        })
        
        if (!res.confirm) return
        
        uni.showLoading({
          title: '删除中...',
          mask: true
        })
        
        const res2 = await this.$api.user.history.delete(id)
        
        if (res2.code === 200) {
          // 从列表中移除该记录
          const index = this.historyList.findIndex(item => item.id === id)
          if (index > -1) {
            this.historyList.splice(index, 1)
          }
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } else {
          throw new Error(res2.message || '删除失败')
        }
      } catch (error) {
        console.error('删除浏览记录失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 清空浏览历史
    async handleClearAll() {
      try {
        const res = await uni.showModal({
          title: '提示',
          content: '确定要清空全部浏览记录吗？',
          confirmColor: '#ff5500'
        })
        
        if (!res.confirm) return
        
        uni.showLoading({
          title: '清空中...',
          mask: true
        })

        const res2 = await this.$api.user.history.clear()
        
        if (res2.code === 200) {
          // 清空列表
          this.historyList = []
          
          uni.showToast({
            title: '清空成功',
            icon: 'success'
          })
        } else {
          throw new Error(res2.message || '清空失败')
        }
      } catch (error) {
        console.error('清空浏览历史失败:', error)
        uni.showToast({
          title: '清空失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      await this.loadHistoryList(true)
    },

    // 加载更多
    loadMore() {
      if (this.loadMoreStatus === 'loading' || !this.hasMore) return
      this.pageNum++
      this.loadHistoryList()
    },

    // 跳转到商品详情
    toProductDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${productId}`
      })
    },

    // 去逛逛
    goBrowse() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.history-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.history-scroll {
  height: 100vh;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  
  .clear-btn {
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 20rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;

  image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }

  .go-browse {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: linear-gradient(to right, #ff7300, #ff5500);
    color: #ffffff;
    font-size: 28rpx;
    border-radius: 40rpx;

    &:active {
      opacity: 0.9;
    }
  }
}

.history-list {
  padding: 20rpx;

  .history-item {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .product-info {
      flex: 1;
      display: flex;
      align-items: center;

      .product-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }

      .info {
        flex: 1;

        .name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .price {
          font-size: 32rpx;
          color: #ff5500;
          font-weight: bold;
          margin-bottom: 10rpx;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .delete-btn {
      padding: 20rpx;
      margin: -20rpx;
    }
  }
}
</style> 